package cn.edu.zzuli.nothinglink.service.impl;

import cn.edu.zzuli.nothinglink.constant.LiveConst;
import cn.edu.zzuli.nothinglink.entity.*;
import cn.edu.zzuli.nothinglink.mapper.CourseMapper;
import cn.edu.zzuli.nothinglink.mapper.LiveInfoMapper;
import cn.edu.zzuli.nothinglink.mapper.LiveRecordMapper;
import cn.edu.zzuli.nothinglink.mapper.SignMapper;
import cn.edu.zzuli.nothinglink.service.LiveRecordService;
import cn.edu.zzuli.nothinglink.vo.LiveRecordsVo;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author suzyyy
 * @since 2021-04-08
 */
@Service
@Slf4j
public class LiveRecordServiceImpl extends ServiceImpl<LiveRecordMapper, LiveRecord> implements LiveRecordService {

    @Resource
    LiveRecordMapper liveRecordMapper;

    @Resource
    LiveInfoMapper liveInfoMapper;

    @Resource
    SignMapper signMapper;

    @Resource
    CourseMapper courseMapper;

    @Autowired
    RedisTemplate<String, Object> redisTemplate;

    /**
     * 获取该教师的全部直播记录。
     * @param teaId
     * @return
     */
    @Override
    public R getLiveRecordsById(Integer teaId) {
        //查询该教师的直播间。
        LiveInfo myLive = liveInfoMapper.selectOne(
                new LambdaQueryWrapper<LiveInfo>().eq(LiveInfo::getLiveBelongTeaId, teaId)
        );

        List<LiveRecord> liveRecords = liveRecordMapper.selectList(
                new LambdaQueryWrapper<LiveRecord>().eq(LiveRecord::getLiveId, myLive.getLiveId())
        );

        List<LiveRecordsVo> recordsVoList = new ArrayList<>();

        liveRecords.forEach(record -> {

            AtomicReference<Integer> totalNumber = new AtomicReference<>(0);
            StringBuilder realNumberInfo = new StringBuilder();
            StringBuilder classNames = new StringBuilder();

            String liveClassJson = record.getLiveClassJson();
            List<Classes> classInfos = JSONArray.parseArray(liveClassJson, Classes.class);
            record.setLiveClassJson("");
            //遍历班级信息
            AtomicBoolean isFirst = new AtomicBoolean(true);
            classInfos.forEach(c -> {
                totalNumber.set(totalNumber.get() + c.getClassStuNumber());
                if (isFirst.get()) {
                    classNames.append(c.getClassRealName());
                    isFirst.set(false);
                }else {
                    classNames.append("，").append(c.getClassRealName());
                }
            });
            Course course = courseMapper.selectById(record.getLiveCourseId());
            //获取当前记录的签到人数。这里偷懒了，没有在直播结束时，直接将签到的人数和回答问题的人数保存到数据库中。
            //所以我们要获取签到人数的话，只能先查询当前直播记录对应的 sign记录，以此来获取signUUId,然后获取对应UUID的签到人数。。
            List<Sign> signs = signMapper.selectList(new LambdaQueryWrapper<Sign>().eq(Sign::getLiveRecordId, record.getRecordId()));

            isFirst.set(true);
            if (signs.size() != 0) {
                signs.forEach(sign -> {
                    Set<Object> members = redisTemplate.opsForHash().keys(LiveConst.LIVE_SIGN.KEY() + sign.getLiveUuid() + ":" + sign.getSignUuid());
                    //因为有一个占位的对象，所以如果有该签到数据，那肯定不为0。这里为了出现bug,添加这个判断
                    if (members.size() != 0) {
                        if (isFirst.get()) {
                            realNumberInfo.append(members.size() - 1);
                            isFirst.set(false);
                        }else {
                            realNumberInfo.append("，").append(members.size() - 1);
                        }
                    }
                });
            }else {
                realNumberInfo.append("0");
            }

            recordsVoList.add(
                    new LiveRecordsVo().setRecord(record)
                            .setRealNumber(realNumberInfo.toString())
                            .setTotalNumber(totalNumber.get())
                            .setCourseName(course.getCourseName())
                            .setClassNames(classNames.toString())
            );


        });

        return R.success().add("records", recordsVoList);
    }
}
